# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from pprint import pprint
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "横琴琴心保重大疾病保险"
    # 生成产品数据
    def genProductInfo(self):

        planI = {

            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,36)],
                #性别
                "gender":["M","F"],
                #保障期限
                "expire":["70岁","80岁","终身"],
                #交费间隔
                "interval":["0","10","20","30"],
                #交费方式
                "payType":["年交"],
                #保障金额
                "money":["100000","200000","300000","500000"],
                #恶性肿瘤豁免
                "seriousCancer":["0","1"],
                #身故全残
                "seriousDeath":["0","1"],
                #少儿特定疾病
                "childrenDisease":["0"],
                #心脑血管疾病
                "heartHeadDisease":["0","1"],
                #投保对象
                "payObject":["本人"]
            },
            "planB":{
                # 年龄段
                "year": [str(i) for i in range(36, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费间隔
                "interval": ["0", "5", "10", "20"],
                # 交费方式
                "payType": ["年交"],
                # 保障金额
                "money": ["100000", "200000", "300000","500000"],
                # 恶性肿瘤豁免
                "seriousCancer": ["0", "1"],
                # 身故全残
                "seriousDeath": ["0", "1"],
                # 少儿特定疾病
                "childrenDisease": ["0"],
                # 心脑血管疾病
                "heartHeadDisease": ["0", "1"],
                # 投保对象
                "payObject": ["本人"]
            },
            "planC":{
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费间隔
                "interval": ["0","10", "15"],
                # 交费方式
                "payType": ["年交"],
                # 保障金额
                "money": ["100000", "200000", "300000", "500000"],
                # 恶性肿瘤豁免
                "seriousCancer": ["0", "1"],
                # 身故全残
                "seriousDeath": ["0", "1"],
                # 少儿特定疾病
                "childrenDisease": ["0"],
                # 心脑血管疾病
                "heartHeadDisease": ["0", "1"],
                # 投保对象
                "payObject": ["本人"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费间隔
                "interval": ["0", "5", "10"],
                # 交费方式
                "payType": ["年交"],
                # 保障金额
                "money": ["100000", "200000", "300000", "500000"],
                # 恶性肿瘤豁免
                "seriousCancer": ["0", "1"],
                # 身故全残
                "seriousDeath": ["0", "1"],
                # 少儿特定疾病
                "childrenDisease": ["0"],
                # 心脑血管疾病
                "heartHeadDisease": ["0", "1"],
                # 投保对象
                "payObject": ["本人/子女"]
            }

        }
        planII = {

            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,36)],
                #性别
                "gender":["M","F"],
                #保障期限
                "expire":["70岁","80岁","终身"],
                #交费间隔
                "interval":["0","10","20","30"],
                #交费方式
                "payType":["年交"],
                #保障金额
                "money":["100000","200000","300000","500000"],
                #恶性肿瘤豁免
                "seriousCancer":["0","1"],
                #身故全残
                "seriousDeath":["0","1"],
                #少儿特定疾病
                "childrenDisease":["0"],
                #心脑血管疾病
                "heartHeadDisease":["0","1"],
                #投保对象
                "payObject":["本人"]
            },
            "planB":{
                # 年龄段
                "year": [str(i) for i in range(36, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费间隔
                "interval": ["0", "5", "10", "20"],
                # 交费方式
                "payType": ["年交"],
                # 保障金额
                "money": ["100000", "200000", "300000", "500000"],
                # 恶性肿瘤豁免
                "seriousCancer": ["0", "1"],
                # 身故全残
                "seriousDeath": ["0", "1"],
                # 少儿特定疾病
                "childrenDisease": ["0"],
                # 心脑血管疾病
                "heartHeadDisease": ["0", "1"],
                # 投保对象
                "payObject": ["本人"]
            },
            "planC":{
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费间隔
                "interval": ["0", "10", "15"],
                # 交费方式
                "payType": ["年交"],
                # 保障金额
                "money": ["100000", "200000", "300000", "500000"],
                # 恶性肿瘤豁免
                "seriousCancer": ["0", "1"],
                # 身故全残
                "seriousDeath": ["0", "1"],
                # 少儿特定疾病
                "childrenDisease": ["0"],
                # 心脑血管疾病
                "heartHeadDisease": ["0", "1"],
                # 投保对象
                "payObject": ["本人/子女"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 交费间隔
                "interval": ["0", "5", "10"],
                # 交费方式
                "payType": ["年交"],
                # 保障金额
                "money": ["100000", "200000", "300000", "500000"],
                # 恶性肿瘤豁免
                "seriousCancer": ["0", "1"],
                # 身故全残
                "seriousDeath": ["0"],
                # 少儿特定疾病
                "childrenDisease": ["0"],
                # 心脑血管疾病
                "heartHeadDisease": ["0", "1"],
                # 投保对象
                "payObject": ["配偶/父母"]
            }

        }

        for k in planI:
            for v in product(planI[k]["year"],planI[k]["gender"],planI[k]["expire"],planI[k]["interval"],planI[k]["payType"],planI[k]["money"],planI[k]["seriousCancer"],planI[k]["seriousDeath"],planI[k]["childrenDisease"],planI[k]["heartHeadDisease"],planI[k]["payObject"]):
                if v[3] == "0":payType = "一次交清"
                else:
                    payType = "年交"
                if v[6] == "1":seriousCancer = v[5]
                else:
                    seriousCancer = "0"
                if v[7] == "1":seriousDeath = v[5]
                else:
                    seriousDeath = "0"
                if v[8] == "1":childrenDisease = v[5]
                else:
                    childrenDisease = "0"
                if v[9] == "1":heartHeadDisease = v[5]
                else:
                    heartHeadDisease = "0"

                data = Helper.formatProductInfo( planI[k],v )
                data["payType"] = payType
                data["seriousCancer"] = seriousCancer
                data["seriousDeath"] = seriousDeath
                data["childrenDisease"] = childrenDisease
                data["heartHeadDisease"] = heartHeadDisease
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format( **data ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format( **data ) )
        for k in planII:
            for v in product(planII[k]["year"],planII[k]["gender"],planII[k]["expire"],planII[k]["interval"],planII[k]["payType"],planII[k]["money"],planII[k]["seriousCancer"],planII[k]["seriousDeath"],planII[k]["childrenDisease"],planII[k]["heartHeadDisease"],planII[k]["payObject"]):
                if v[3] == "0":payType = "一次交清"
                else:
                    payType = "年交"

                if v[6] == "1":seriousCancer = v[5]
                else:
                    seriousCancer = "0"
                if v[7] == "1":
                    seriousDeath = v[5]
                else:
                    seriousDeath = "0"
                if v[8] == "1":
                    childrenDisease = v[5]
                else:
                    childrenDisease = "0"
                if v[9] == "1":
                    heartHeadDisease = v[5]
                else:
                    heartHeadDisease = "0"
                data = Helper.formatProductInfo( planII[k],v )
                data["payType"] = payType
                data["payType"] = payType
                data["seriousCancer"] = seriousCancer
                data["seriousDeath"] = seriousDeath
                data["childrenDisease"] = childrenDisease
                data["heartHeadDisease"] = heartHeadDisease
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):
        year = str(2020-int(dt["year"]))
        sex = "0" if dt["gender"] == "M" else "1"
        expire = dt["expire"].replace("岁","") if "岁" in dt["expire"] else "full"
        libCode = ""
        if dt["seriousCancer"] != "0":
            libCode += "1"
        else:
            pass
        if dt["seriousDeath"] != "0":
            libCode += "2"
        else:
            pass
        if dt["childrenDisease"] != "0":
            libCode += "3"
        else:
            pass
        if dt["heartHeadDisease"] != "0":
            libCode += "4"
        else:
            pass
        data = {"birthDate": ""+year+"-01-01", "insurant": {"birthday": ""+year+"-01-01", "genderCode": sex}, "gender": sex,
                "sumAssured": dt["money"], "coverageList": [
                {"isMain": "true", "code": "16350", "name": "横琴琴心保重大疾病保险", "id": "HQL00058", "payMethod": "12" if dt["payType"] == "年交" else "0",
                 "pay": "term_"+dt["interval"]+"" if dt["interval"] != "0" else "single",
                 "liabilities": [{"liabilityName": "横琴琴心保重大疾病保险", "liabilityCode": libCode, "amnt": dt["money"]}]}],
                "saleItemId": 10077, "goodsId": 10077, "packageId": 236, "planId": "null", "pay": "term_5",
                "insurePeriod": "to_"+expire+"", "isReturnAmount": "false", "paymentFreq": "12", "payFreq": "12",
                "policyPeriodNumber": "to_"+expire+"", "premPeriodNumber": "term_"+dt["interval"]+"" if dt["interval"] != "0" else "single"}
        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload,verify=False)
        if r.status_code == 200 and r.json()["success"]:
            pprint( r.json( ) )
            price = r.json()["data"]["goodsPremium"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask( data )
            print("\n/*产品价格数据更新失败:%d*/"%dt["id"])

    def main(self, mysql):
        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            self.requestJson(dt, mysql)

    def startProcess(self):
        threads = []
        for i in range(10):
            mysql = MysqlClient()
            t = Thread(target=self.main, args=(mysql,))
            t.start()
            threads.append(t)
        for t in threads:
            t.join()

